﻿using System.Text;

namespace Algorithm;

public class RomanNumerals
{
    static int RomanNumber(string str) => str switch
    {
        "I" => 1,
        "IV" => 4,
        "V" => 5,
        "IX" => 9,
        "X" => 10,
        "XL" => 40,
        "L" => 50,
        "XC" => 90,
        "C" => 100,
        "CD" => 400,
        "D" => 500,
        "CM" => 900,
        "M" => 1000,
        _ => throw new ArgumentException("Invalid Roman numeral")
    };

    /// <summary>
    /// 数字转换为罗马字符串
    /// </summary>
    /// <param name="n"></param>
    /// <returns></returns>
    public static string ToRoman(int n)
    {
        var values = new int[] { 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 };
        var symbols = new string[] { "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I" };
        var result = new StringBuilder();
        for (int i = 0; i < values.Length && n > 0; i++)
        {
            while (n >= values[i])
            {
                result.Append(symbols[i]);
                n -= values[i];
            }
        }
        return result.ToString();
    }

    /// <summary>
    /// 罗马字符串转换为数字
    /// </summary>
    /// <param name="romanNumeral"></param>
    /// <returns></returns>
    public static int FromRoman(string romanNumeral)
    {
        var symbols = new string[] { "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I" };
        var arr = romanNumeral.ToCharArray();
        int v = 0;
        for (int i = 0; i < arr.Length; i++)
        {
            if (i != arr.Length - 1 && symbols.Contains(arr[i].ToString() + arr[i+1].ToString()))
            {
                v += RomanNumber(arr[i].ToString() + arr[i+1].ToString());
                i++;
            }
            else
            {
                v += RomanNumber(arr[i].ToString());
            }
        }
        return v;
    }
}
